<template>
  <CommonDialog
    v-model="state.dialogVisible"
    :border="true"
    width="70%"
    :title="dialogTitle"
    @ok="handleConfirm"
    @cancel="state.dialogVisible = false"
    @closed="state.dialogVisible = false"
  >
    <el-row>
      <el-col :span="6" v-loading="state.loading" style="padding: 5px">
        <div style="display: flex; align-items: center">
          <el-input
            v-model="state.searchKey"
            class="w-org-picker-s-input"
            clearable
            placeholder="搜索部门"
            prefix-icon="search"
          />
          <el-button type="primary" icon="search" @click="handleDeptQuery"
            >查询</el-button
          >
        </div>
        <div class="card-container">
          <el-card shadow="never" :body-style="{ padding: '10px' }">
            <div class="card-content-full" style="height: 450px !important">
              <el-scrollbar>
                <el-tree
                  ref="deptTreeRef"
                  :check-strictly="true"
                  class="custom-tree"
                  :data="treeOptions.dataList"
                  highlight-current
                  node-key="id"
                  lazy
                  v-loading="treeOptions.loading"
                  :filter-node-method="handleFilterNode"
                  :load="lazyLoadNode"
                  :props="treeOptions.props"
                  :show-checkbox="props.type === 'dept'"
                  check-on-click-node
                  @node-click="handleDeptClick"
                  @check-change="handleDeptCheck"
                >
                  <template #default="{ node, data }">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="data.deptFullName"
                      placement="top"
                    >
                      <span>{{ node.label }}</span>
                    </el-tooltip>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="18">
        <vab-query-form>
          <vab-query-form-top-panel>
            <el-form
              :inline="true"
              label-width="0px"
              :model="tableOptions.queryForm"
            >
              <el-row :gutter="5">
                <el-col :span="5">
                  <el-input
                    v-model="tableOptions.queryForm.userName"
                    placeholder="姓名"
                  />
                </el-col>
                <el-col :span="5">
                  <el-input
                    v-model="tableOptions.queryForm.labor"
                    placeholder="工号"
                  />
                </el-col>
                <el-col :span="5">
                  <el-input
                    v-model="tableOptions.queryForm.mobilePhone"
                    placeholder="手机号"
                  />
                </el-col>
                <el-col :span="9">
                  <el-button
                    icon="refresh-left"
                    type="warning"
                    @click="handleResetQuery"
                  >
                    重置
                  </el-button>
                  <el-button
                    icon="Search"
                    type="primary"
                    @click="queryTableData"
                  >
                    查询
                  </el-button>
                </el-col>
              </el-row>
            </el-form>
          </vab-query-form-top-panel>
        </vab-query-form>
        <el-tabs
          ref="tabsRef"
          v-model="state.currentTabs"
          :stretch="false"
          type="border-card"
        >
          <el-tab-pane label="用户" name="0">
            <el-table
              ref="tableRef"
              v-loading="tableOptions.loading"
              border
              stripe
              :data="tableOptions.dataList"
              :height="tableOptions.height"
              :cell-style="tableStyle.cellStyle"
              :header-cell-style="tableStyle.headerCellStyle"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange"
              @row-click="handleRowClick"
            >
              <el-table-column
                align="center"
                show-overflow-tooltip
                type="selection"
                width="60"
              />
              <el-table-column label="序号" type="index" width="60">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="姓名"
                prop="userName"
                width="100"
              />
              <el-table-column
                align="center"
                label="工号"
                prop="labor"
                width="100"
              />
              <el-table-column
                align="center"
                label="手机号码"
                prop="mobilePhone"
                width="120"
              />
              <el-table-column
                align="center"
                label="状态"
                prop="statusDesc"
                width="100"
              />
              <el-table-column
                align="center"
                label="所属部门"
                prop="deptNames"
                width="160"
              />
              <el-table-column
                align="center"
                label="主部门"
                prop="mainDeptName"
                width="100"
              />
              <el-table-column
                align="center"
                label="员工岗位"
                prop="position"
                width="120"
              />
              <el-table-column
                align="center"
                label="员工性别"
                prop="userSexDesc"
                width="90"
              />
              <el-table-column
                align="center"
                label="办公电话"
                prop="telephone"
                width="120"
              />
            </el-table>
            <el-pagination
              background
              :current-page="tableOptions.pagination.current"
              :layout="tableOptions.pagination.layout"
              :page-size="tableOptions.pagination.size"
              :total="tableOptions.pagination.total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </el-tab-pane>
        </el-tabs>
        <div class="w-org-items" v-if="state.selectedList.length > 0">
          <el-tag
            v-for="(tag, index) in state.selectedList"
            :key="tag.id"
            closable
            size="large"
            @close="handleReduce(index, tag.id)"
            style="margin-right: 10px"
          >
            {{ tag.text }}
          </el-tag>
        </div>
      </el-col>
    </el-row>
  </CommonDialog>
</template>
<script setup lang="ts">
import CommonDialog from "@/components/commonDialog.vue";
import { reactive, ref } from "vue";
import { queryDeptTree } from "@/api/admin/org/dept/";
import { queryStaffTable } from "@/api/admin/org/staff/";
import type { MultiTagsItem } from "./form/FormComponentMixin";
import { getTableHeight } from "@/utils/util";
import { useTree } from "@/hooks/tree";
import type { BasicTree } from "@/hooks/tree";
import { useTable, BasicTableProps } from "@/hooks/table";
import { TreeOptionProps } from "element-plus/es/components/tree/src/tree.type.mjs";

const props = defineProps({
  title: {
    type: String,
    default: "请选择"
  },
  type: {
    type: String,
    default: "dept"
  },
  multiple: {
    type: Boolean,
    default: false
  }
});

const _value = defineModel<MultiTagsItem[]>();
const deptTreeRef = ref(null);
const tableRef = ref(null);
const tabsRef = ref(null);

const emits = defineEmits(["ok"]);

const dialogTitle = computed(() => {
  if (props.type === "dept") {
    return props.title + "部门";
  } else if (props.type === "user") {
    return props.title + "用户";
  }
});

const state = reactive({
  dialogTitle: props.title,
  dialogVisible: false,
  searchKey: "",
  loading: false,
  selectedList: [] as Array<{ id: string; text: string }>,
  currentTabs: "0"
});

const treeOptions = reactive<BasicTree>({
  queryForm: { pid: "0" },
  props: {
    children: "children",
    label: "text",
    isLeaf: "leaf"
  } as PropType<TreeOptionProps>,
  queryFunction: queryDeptTree
});
const { queryTreeData, filterNode, lazyLoadNode } = useTree(treeOptions);

const tableOptions = reactive<BasicTableProps>({
  height: getTableHeight(1, true, true) - 165,
  autoLoad: true,
  queryForm: {
    userName: "",
    labor: "",
    mobilePhone: "",
    deptFullId: ""
  },
  queryFunction: queryStaffTable,
  descs: ["create_time"]
});
const {
  tableStyle,
  queryTableData,
  handleSelectionChange,
  handleResetQuery,
  handleRowClick,
  handleSizeChange,
  handleCurrentChange,
  handleSortChange,
  handleToggleMultiple
} = useTable(tableOptions, tableRef);

const handleDeptQuery = () => {
  return queryTreeData({ deptFullName: state.searchKey, pid: null });
};

watch(
  () => state.searchKey,
  val => {
    deptTreeRef.value.filter(val);
  }
);

watch(
  () => props.multiple,
  val => {
    handleToggleMultiple(val);
  }
);

watch(
  () => tableOptions.dataSelections,
  (val, old) => {
    if (props.type === "user") {
      //过滤出不在state.selectedList中的行并加入到state.selectedList中。
      if (props.multiple) {
        val.forEach(n => {
          if (!state.selectedList.some(m => m.id === n.id)) {
            state.selectedList.push({ id: n.id, text: n.userName });
          }
        });
      } else {
        state.selectedList = [];
        const n = tableOptions.dataSelections[0];
        state.selectedList.push({ id: n.id, text: n.userName });
      }
    }
  }
);

const handleFilterNode = (value, data) => {
  if (!value) {
    queryTreeData({ pid: "0" });
    return true;
  }
  filterNode({ deptName: value, pid: null });
};

const handleDeptClick = data => {
  tableOptions.queryForm.deptFullId = data.id;
  queryTableData();
};

const handleDeptCheck = (node, checked, childChecked) => {
  if (props.type === "dept") {
    if (checked) {
      if (!state.selectedList.some(n => n.id === node.id)) {
        state.selectedList.push({ id: node.id, text: node.text });
        if (!props.multiple) {
          state.selectedList
            .filter(n => n.id != node.id)
            .forEach(n => deptTreeRef.value.setChecked(n.id, false));
          state.selectedList = [
            state.selectedList[state.selectedList.length - 1]
          ];
        }
      }
    } else {
      state.selectedList = state.selectedList.filter(n => n.id != node.id);
      deptTreeRef.value.setChecked(node.id, false);
    }
  }
};

const handleConfirm = () => {
  const list = state.selectedList.map(item => {
    return {
      id: item.id,
      text: item.text
    };
  });
  state.dialogVisible = false;
  emits("ok", list);
};

const handleReduce = (index, id) => {
  if (props.type === "dept") {
    deptTreeRef.value.setChecked(id, false);
    state.selectedList.splice(index, 1);
  } else {
    const list = tableOptions.dataList.filter(n => n.id === id);
    if (list && list.length > 0) {
      tableRef.value.toggleRowSelection(list[0], false);
    }
    state.selectedList.splice(index, 1);
  }
};

const show = () => {
  state.dialogVisible = true;
  state.selectedList = [];
  queryTreeData();
};

const close = () => {
  state.selectedList = [];
  state.dialogVisible = false;
};

defineExpose({ show, close });
</script>

<style scoped lang="scss">
.w-org-items {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;
  margin-left: 10px;
}
</style>
